/*

File: HelloWorldAppDelegate.m
 //  HelloWorld
 //
 //  Created by Martin Le C. on 6/8/09.
 //  Copyright 2009 __MyCompanyName__. All rights reserved.
 //

*/

#import "HelloWorldAppDelegate.h"
#import "MyViewController.h"
#import "SigningInViewController.h"
#import "Session.h"
#import "BuddyListViewController.h"
#import "ChatViewController.h"
#import "Msg.h"
@implementation HelloWorldAppDelegate
@synthesize window;
@synthesize myViewController;
@synthesize navController;
@synthesize signingInViewController;
@synthesize buddyListViewController;
@synthesize chatViewController;
@synthesize ss;
@synthesize LoginID;
#pragma mark application events
- (void)applicationDidFinishLaunching:(UIApplication *)application {
	// create window and set up table view controller
	[self createEditableCopyOfDatabaseIfNeeded];
	[self initializeDatabase];
	//[self copyDatabaseIfNeeded];
	//[Msg getInitialData:[self getDBPath]];
	//NSLog(@"Error while creating add statement. '%s'", sqlite3_errmsg(database));
	signingInViewController = [[SigningInViewController alloc] initWithNibName:@"SigningIn" bundle:[NSBundle mainBundle]];
	buddyListViewController = [[BuddyListViewController alloc] initWithNibName:@"BuddyListView" bundle:[NSBundle mainBundle]];
	chatViewController = [[ChatViewController alloc] initWithNibName:@"DetailsChat" bundle:[NSBundle mainBundle]];
	[window addSubview:navController.view];
	[window makeKeyAndVisible];
}
// delete all record to the database, then close it.
- (void)applicationWillTerminate:(UIApplication *)application {
    // delete here :)
    // Close the database.
    if (sqlite3_close(database) != SQLITE_OK) {
        NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(database));
    }
}

- (void) signIn:(NSString*)u p:(NSString*)p {
	if ([[u stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0 || [[p stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Sign-In Problem" message:@"You must enter an ID and password" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
		[alert show];
		[alert release];
	} else {
		LoginID = u;
		NSMutableArray* account = [[NSMutableArray alloc] init];
		[account addObject:u];
		[account addObject:p];
		NSThread* loginThread = [[NSThread alloc] initWithTarget:self selector:@selector(connect:) object:account];
		[loginThread start];
		[self signingInView:(NSString*)u];
		
	}
}
/*
- (void) signIn:(NSString*)u p:(NSString*)p {
	NSMutableArray* list = [[NSMutableArray alloc] init];
	YahooGroup* yg = [[YahooGroup alloc] init:@"yahoo"];
	[yg addUser:[[YahooUser alloc] init:@"yahoo_fucking"]];
	[yg addUser:[[YahooUser alloc] init:@"yahoo_fucking2"]];
	[list addObject:yg];
	yg = [[YahooGroup alloc] init:@"yahoo2"];
	[yg addUser:[[YahooUser alloc] init:@"yahoo_fucking"]];
	[yg addUser:[[YahooUser alloc] init:@"yahoo_fucking2"]];
	[list addObject:yg];
	Msg* msg = [[Msg alloc] init];
	msg.f = @"yahoo_fucking";
	msg.to = @"yahoo_fucking2";
	msg.text = @"anh dep trai";
	[msg addMsg:database];
	[Msg finalizeStatements];
	buddyListViewController.dataArray = list;
	[navController pushViewController:buddyListViewController animated:YES];
	
}
 */
- (void) cancelSignIn {
	[ss closeNetwork];
	[navController popToRootViewControllerAnimated:YES];
}
- (void) signingInView:(NSString*)u {
	if (signingInViewController == nil) { 
		signingInViewController = [[SigningInViewController alloc] initWithNibName:@"SigningIn" bundle:[NSBundle mainBundle]];
	}
	signingInViewController.yahooID = u;
	[navController pushViewController:signingInViewController animated:YES];
}
- (void) sendMsg:(NSString*)to msg:(NSString*)msg {
	[ss sendMessage2:LoginID to:to msg:msg];
}
- (void) chatView:(NSString*)buddyID {
	if (chatViewController == nil) { 
		chatViewController = [[ChatViewController alloc] initWithNibName:@"DetailsView" bundle:[NSBundle mainBundle]];
	}
	chatViewController.buddyID = buddyID;
	chatViewController.yahooID = LoginID;
	[chatViewController view];
	[chatViewController getChatText:[self getListOfAllMsgFromThisBuddy:buddyID]];
	[navController pushViewController:chatViewController animated:YES];
}
- (void) releaseViews {
	//[myViewController dealloc];
	//[signingInViewController dealloc];
}
- (void) connect:(id)target{
	NSLog(@"%@", [target objectAtIndex:1]);
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	ss = [[Session alloc] initWithDelegate:self];
	[ss login:[target objectAtIndex:0] p:[target objectAtIndex:1]];
	[pool release];
}
#pragma mark delegates from Session
- (void) Session:(Session *) session didReceivedBuddyList:(BOOL)did {
	buddyListViewController.dataArray = ss.groups;
	[navController pushViewController:buddyListViewController animated:YES];
}
- (void) Session:(Session *) session didReceivedPM:(NSString *)from to:(NSString*)to msg:(NSString*)msg {
	NSLog(@"did received PM");
	Msg* msgObject = [[Msg alloc] init];
	msgObject.f = from;
	msgObject.to = to;
	msgObject.text= msg;
	[msgObject addMsg:database];
	//[Msg finalizeStatements];
	if ([navController.visibleViewController isKindOfClass:[BuddyListViewController class]]) {
		NSLog(@"aa");
		[buddyListViewController receiveMsg:msgObject.f];
	} else if ([navController.view isKindOfClass:[ChatViewController class]]) {
		NSLog(@"bbb");
		
	}
	[chatViewController  receiveMsg:msgObject];
}
- (void) Session:(Session *)session didReceivedBudStatus:(NSString *)buddyId {

}
- (void) Session:(Session *)session errorLogin:(NSString*)error {
	NSLog(@"did error");
	[navController popViewControllerAnimated:YES];
	UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Sign-In Problem" message:error delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
	[alert show];
	[alert release];
	[navController popToRootViewControllerAnimated:YES];
	[ss closeNetwork];
	[ss release];
	
}
#pragma mark database methods
// Creates a writable copy of the bundled default database in the application Documents directory.
- (void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"chat.sqlite"];
    success = [fileManager fileExistsAtPath:writableDBPath];
	NSLog(@"succcess:%i", success);
    if (success) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"chat.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}
// Open the database connection and retrieve minimal information for all objects.
- (void)initializeDatabase {
    // The database is stored in the application bundle. 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"chat.sqlite"];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &database) != SQLITE_OK) {
        // Even though the open failed, call close to properly clean up resources.
        sqlite3_close(database);
        NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
        // Additional error handling, as appropriate...
    }
}
- (NSMutableArray*)getListOfAllMsgFromThisBuddy:(NSString*)buddyId {
	
	//get the data from the database and fill the array.
	NSMutableArray* listOfMsg = [[NSMutableArray alloc] init];
	sqlite3_stmt *statement;
	const char *sql = "SELECT f,t,text FROM msg WHERE f=? OR t=?";
	if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
		sqlite3_bind_text(statement, 1, [buddyId UTF8String], -1, SQLITE_TRANSIENT);
		sqlite3_bind_text(statement, 2, [buddyId UTF8String], -1, SQLITE_TRANSIENT);
		while(sqlite3_step(statement) == SQLITE_ROW)
		{
			//populate the object with the data.
			Msg *msg = [[Msg alloc] init];
			msg.f = [[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)] copy];
			msg.to = [[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 1)] copy];
			msg.text = [[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 2)] copy];;
			//Add the object to the array.
			[listOfMsg addObject:msg];
			[msg release];
		}
		//finalize the statement, so it can be used again.
		 sqlite3_finalize(statement);
	}
	//Close the connection.
	else
		sqlite3_close(database);
	NSLog(@"count %i", [listOfMsg count]);
	return listOfMsg;
}
- (void)dealloc {
	[myViewController dealloc];
	[navController release];
	[signingInViewController dealloc];
	[window release];
	[super dealloc];
}
@end
